package com.ruoyi.nongjt.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.nongjt.domain.CertificateIssuanceStats;
import com.ruoyi.nongjt.mapper.CertificateIssuanceStatsMapper;
import com.ruoyi.nongjt.service.CertificateIssuanceStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 合格证开具数量统计Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service
public class CertificateIssuanceStatsServiceImpl implements CertificateIssuanceStatsService 
{
    @Autowired
    private CertificateIssuanceStatsMapper certificateIssuanceStatsMapper;

    /**
     * 查询合格证开具数量统计列表
     * 
     * @param certificateIssuanceStats 合格证开具数量统计
     * @return 合格证开具数量统计
     */
    @Override
    public List<CertificateIssuanceStats> selectCertificateIssuanceStatsList(CertificateIssuanceStats certificateIssuanceStats)
    {
        // 智能选择数据源：优先使用统计表，如果数据不足则使用实时数据
        List<CertificateIssuanceStats> statsList = certificateIssuanceStatsMapper.selectStatsFromTable(certificateIssuanceStats);
        
        // 如果统计表数据为空或数据量很少，则使用实时数据
        if (statsList == null || statsList.isEmpty()) {
            // 设置使用实时数据标志
            if (certificateIssuanceStats.getParams() == null) {
                certificateIssuanceStats.setParams(new java.util.HashMap<>());
            }
            certificateIssuanceStats.getParams().put("useRealTime", true);
            statsList = certificateIssuanceStatsMapper.selectRealTimeStatsFromPrint(certificateIssuanceStats);
        }
        
        return statsList;
    }

    /**
     * 从合格证打印表实时统计数据
     * 
     * @param certificateIssuanceStats 查询条件
     * @return 统计结果集合
     */
    @Override
    public List<CertificateIssuanceStats> selectRealTimeStatsFromPrint(CertificateIssuanceStats certificateIssuanceStats)
    {
        return certificateIssuanceStatsMapper.selectRealTimeStatsFromPrint(certificateIssuanceStats);
    }

    /**
     * 从统计表查询数据
     * 
     * @param certificateIssuanceStats 查询条件
     * @return 统计结果集合
     */
    @Override
    public List<CertificateIssuanceStats> selectStatsFromTable(CertificateIssuanceStats certificateIssuanceStats)
    {
        return certificateIssuanceStatsMapper.selectStatsFromTable(certificateIssuanceStats);
    }

    /**
     * 生成统计数据
     * 
     * @param statsDate 统计日期
     * @return 结果
     */
    @Override
    @Transactional
    public int generateStatsData(String statsDate)
    {
        try {
            // 先删除该日期的旧数据
            certificateIssuanceStatsMapper.deleteStatsByDate(statsDate);
            
            // 生成新的统计数据
            CertificateIssuanceStats queryParams = new CertificateIssuanceStats();
            if (queryParams.getParams() == null) {
                queryParams.setParams(new java.util.HashMap<>());
            }
            queryParams.getParams().put("beginTime", statsDate);
            queryParams.getParams().put("endTime", statsDate);
            
            List<CertificateIssuanceStats> statsList = certificateIssuanceStatsMapper.selectRealTimeStatsFromPrint(queryParams);
            
            if (statsList != null && !statsList.isEmpty()) {
                // 设置统计日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse(statsDate);
                for (CertificateIssuanceStats stats : statsList) {
                    stats.setStatsDate(date);
                    stats.setCreateTime(DateUtils.getNowDate());
                    stats.setUpdateTime(DateUtils.getNowDate());
                }
                
                return certificateIssuanceStatsMapper.batchInsertStats(statsList);
            }
            
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("生成统计数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 批量生成统计数据
     * 
     * @param beginDate 开始日期
     * @param endDate 结束日期
     * @return 结果
     */
    @Override
    @Transactional
    public int batchGenerateStatsData(String beginDate, String endDate)
    {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdf.parse(beginDate);
            Date endDateObj = sdf.parse(endDate);
            
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            
            int totalCount = 0;
            while (!calendar.getTime().after(endDateObj)) {
                String currentDate = sdf.format(calendar.getTime());
                int count = generateStatsData(currentDate);
                totalCount += count;
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            return totalCount;
        } catch (Exception e) {
            throw new RuntimeException("批量生成统计数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 刷新统计数据
     * 
     * @param statsDate 统计日期
     * @return 结果
     */
    @Override
    @Transactional
    public int refreshStatsData(String statsDate)
    {
        return generateStatsData(statsDate);
    }
}
